﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Piece : Tile
{
    [SerializeField] protected SpriteRenderer spRenderer;
    [SerializeField] private TextMesh _text;
    [SerializeField] private List<ParticleSystem> _highlightParticles = new List<ParticleSystem>();
    [SerializeField] private List<ParticleSystem> _completeParticles = new List<ParticleSystem>();
    [SerializeField] private List<ParticleSystem> _hintParticles = new List<ParticleSystem>();
    [SerializeField] private List<ParticleSystem> _connectParticles = new List<ParticleSystem>();

    private readonly List<int> _numbers = new List<int>();
    private Coroutine _showNumberCoroutine;
    private bool _highlight;    

    public override int Order => 2;

    public Color Color
    {
        get => spRenderer.color;
        set => spRenderer.color = value;
    }

    public bool Highlight
    {
        get => _highlight;
        set
        {
            if (value == _highlight) return;
            _highlight = value;
            
            if(value)
            {
                _highlightParticles.ForEach(p=>p.SetColor(Color));
                _highlightParticles.ForEach(p => p.Play());
            }
            else
            {
                _highlightParticles.ForEach(p=>p.Stop());
            }
        }
    }

    public IEnumerable<int> Numbers
    {
        get => _numbers;
        private set
        {
            _numbers.Clear();
            _numbers.AddRange(value.ToList());
            OnSetNumbers();
        }
    }

    private void OnSetNumbers()
    {
        if (_showNumberCoroutine != null)
        {
            StopCoroutine(_showNumberCoroutine);
            _showNumberCoroutine = null;
        }

        _text.gameObject.SetActive(_numbers.Count>0);
        if(_numbers.Count>0)
         _showNumberCoroutine = StartCoroutine(ShowNumbers());
    }

    public void AddHintNumber(int value)
    {
        Numbers = Numbers.ToList().Append(value);
        Debug.Log(string.Join(",",Numbers));
        _hintParticles.ForEach(p=>p.SetColor(Color));
        _hintParticles.ForEach(p=>p.Play());
    }

    public void ClearHints()
    {
        Numbers = Enumerable.Empty<int>();
    }

    public void ShowCompleteEffect()
    {
        _completeParticles.ForEach(p=>p.SetColor(Color));
        _completeParticles.ForEach(p=>p.Play());
    }

    public void ShowConnectEffect()
    {
        _connectParticles.ForEach(p=>p.SetColor(Color));
        _connectParticles.ForEach(p=>p.Play());
    }

    private IEnumerator ShowNumbers()
    {
        Debug.Log(string.Join(",", _numbers.Select(n => n.ToString()).ToArray()));
        while (_numbers.Count>0)
        {
            for (var i = _numbers.Count - 1; i >= 0; i--)       
            {
                _text.text = _numbers[i].ToString();
                yield return new WaitForSeconds(1.5f);
            }
        }
    }
}



